home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2006 December / PCWDEC06.iso / Software / Trial / Paint Shop Pro XI / Data1.cab / calendar.py.0160FC08_F3D9_4869_9D41_C611C16F42D5 < prev    next >
Encoding:
Text File  |  2005-06-08  |  7.7 KB  |  231 lines

  1. """Calendar printing functions
  2.  
  3. Note when comparing these calendars to the ones printed by cal(1): By
  4. default, these calendars have Monday as the first day of the week, and
  5. Sunday as the last (the European convention). Use setfirstweekday() to
  6. set the first day of the week (0=Monday, 6=Sunday)."""
  7.  
  8. import datetime
  9.  
  10. __all__ = ["error","setfirstweekday","firstweekday","isleap",
  11.            "leapdays","weekday","monthrange","monthcalendar",
  12.            "prmonth","month","prcal","calendar","timegm",
  13.            "month_name", "month_abbr", "day_name", "day_abbr"]
  14.  
  15. # Exception raised for bad input (with string parameter for details)
  16. error = ValueError
  17.  
  18. # Constants for months referenced later
  19. January = 1
  20. February = 2
  21.  
  22. # Number of days per month (except for February in leap years)
  23. mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  24.  
  25. # This module used to have hard-coded lists of day and month names, as
  26. # English strings.  The classes following emulate a read-only version of
  27. # that, but supply localized names.  Note that the values are computed
  28. # fresh on each call, in case the user changes locale between calls.
  29.  
  30. class _localized_month:
  31.  
  32.     _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
  33.     _months.insert(0, lambda x: "")
  34.  
  35.     def __init__(self, format):
  36.         self.format = format
  37.  
  38.     def __getitem__(self, i):
  39.         funcs = self._months[i]
  40.         if isinstance(i, slice):
  41.             return [f(self.format) for f in funcs]
  42.         else:
  43.             return funcs(self.format)
  44.  
  45.     def __len__(self):
  46.         return 13
  47.  
  48. class _localized_day:
  49.  
  50.     # January 1, 2001, was a Monday.
  51.     _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]
  52.  
  53.     def __init__(self, format):
  54.         self.format = format
  55.  
  56.     def __getitem__(self, i):
  57.         funcs = self._days[i]
  58.         if isinstance(i, slice):
  59.             return [f(self.format) for f in funcs]
  60.         else:
  61.             return funcs(self.format)
  62.  
  63.     def __len__(self):
  64.         return 7
  65.  
  66. # Full and abbreviated names of weekdays
  67. day_name = _localized_day('%A')
  68. day_abbr = _localized_day('%a')
  69.  
  70. # Full and abbreviated names of months (1-based arrays!!!)
  71. month_name = _localized_month('%B')
  72. month_abbr = _localized_month('%b')
  73.  
  74. # Constants for weekdays
  75. (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
  76.  
  77. _firstweekday = 0                       # 0 = Monday, 6 = Sunday
  78.  
  79. def firstweekday():
  80.     return _firstweekday
  81.  
  82. def setfirstweekday(weekday):
  83.     """Set weekday (Monday=0, Sunday=6) to start each week."""
  84.     global _firstweekday
  85.     if not MONDAY <= weekday <= SUNDAY:
  86.         raise ValueError, \
  87.               'bad weekday number; must be 0 (Monday) to 6 (Sunday)'
  88.     _firstweekday = weekday
  89.  
  90. def isleap(year):
  91.     """Return 1 for leap years, 0 for non-leap years."""
  92.     return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
  93.  
  94. def leapdays(y1, y2):
  95.     """Return number of leap years in range [y1, y2).
  96.        Assume y1 <= y2."""
  97.     y1 -= 1
  98.     y2 -= 1
  99.     return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
  100.  
  101. def weekday(year, month, day):
  102.     """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
  103.        day (1-31)."""
  104.     return datetime.date(year, month, day).weekday()
  105.  
  106. def monthrange(year, month):
  107.     """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
  108.        year, month."""
  109.     if not 1 <= month <= 12:
  110.         raise ValueError, 'bad month number'
  111.     day1 = weekday(year, month, 1)
  112.     ndays = mdays[month] + (month == February and isleap(year))
  113.     return day1, ndays
  114.  
  115. def monthcalendar(year, month):
  116.     """Return a matrix representing a month's calendar.
  117.        Each row represents a week; days outside this month are zero."""
  118.     day1, ndays = monthrange(year, month)
  119.     rows = []
  120.     r7 = range(7)
  121.     day = (_firstweekday - day1 + 6) % 7 - 5   # for leading 0's in first week
  122.     while day <= ndays:
  123.         row = [0, 0, 0, 0, 0, 0, 0]
  124.         for i in r7:
  125.             if 1 <= day <= ndays: row[i] = day
  126.             day = day + 1
  127.         rows.append(row)
  128.     return rows
  129.  
  130. def prweek(theweek, width):
  131.     """Print a single week (no newline)."""
  132.     print week(theweek, width),
  133.  
  134. def week(theweek, width):
  135.     """Returns a single week in a string (no newline)."""
  136.     days = []
  137.     for day in theweek:
  138.         if day == 0:
  139.             s = ''
  140.         else:
  141.             s = '%2i' % day             # right-align single-digit days
  142.         days.append(s.center(width))
  143.     return ' '.join(days)
  144.  
  145. def weekheader(width):
  146.     """Return a header for a week."""
  147.     if width >= 9:
  148.         names = day_name
  149.     else:
  150.         names = day_abbr
  151.     days = []
  152.     for i in range(_firstweekday, _firstweekday + 7):
  153.         days.append(names[i%7][:width].center(width))
  154.     return ' '.join(days)
  155.  
  156. def prmonth(theyear, themonth, w=0, l=0):
  157.     """Print a month's calendar."""
  158.     print month(theyear, themonth, w, l),
  159.  
  160. def month(theyear, themonth, w=0, l=0):
  161.     """Return a month's calendar string (multi-line)."""
  162.     w = max(2, w)
  163.     l = max(1, l)
  164.     s = ("%s %r" % (month_name[themonth], theyear)).center(
  165.                  7 * (w + 1) - 1).rstrip() + \
  166.          '\n' * l + weekheader(w).rstrip() + '\n' * l
  167.     for aweek in monthcalendar(theyear, themonth):
  168.         s = s + week(aweek, w).rstrip() + '\n' * l
  169.     return s[:-l] + '\n'
  170.  
  171. # Spacing of month columns for 3-column year calendar
  172. _colwidth = 7*3 - 1         # Amount printed by prweek()
  173. _spacing = 6                # Number of spaces between columns
  174.  
  175. def format3c(a, b, c, colwidth=_colwidth, spacing=_spacing):
  176.     """Prints 3-column formatting for year calendars"""
  177.     print format3cstring(a, b, c, colwidth, spacing)
  178.  
  179. def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing):
  180.     """Returns a string formatted from 3 strings, centered within 3 columns."""
  181.     return (a.center(colwidth) + ' ' * spacing + b.center(colwidth) +
  182.             ' ' * spacing + c.center(colwidth))
  183.  
  184. def prcal(year, w=0, l=0, c=_spacing):
  185.     """Print a year's calendar."""
  186.     print calendar(year, w, l, c),
  187.  
  188. def calendar(year, w=0, l=0, c=_spacing):
  189.     """Returns a year's calendar as a multi-line string."""
  190.     w = max(2, w)
  191.     l = max(1, l)
  192.     c = max(2, c)
  193.     colwidth = (w + 1) * 7 - 1
  194.     s = repr(year).center(colwidth * 3 + c * 2).rstrip() + '\n' * l
  195.     header = weekheader(w)
  196.     header = format3cstring(header, header, header, colwidth, c).rstrip()
  197.     for q in range(January, January+12, 3):
  198.         s = (s + '\n' * l +
  199.              format3cstring(month_name[q], month_name[q+1], month_name[q+2],
  200.                             colwidth, c).rstrip() +
  201.              '\n' * l + header + '\n' * l)
  202.         data = []
  203.         height = 0
  204.         for amonth in range(q, q + 3):
  205.             cal = monthcalendar(year, amonth)
  206.             if len(cal) > height:
  207.                 height = len(cal)
  208.             data.append(cal)
  209.         for i in range(height):
  210.             weeks = []
  211.             for cal in data:
  212.                 if i >= len(cal):
  213.                     weeks.append('')
  214.                 else:
  215.                     weeks.append(week(cal[i], w))
  216.             s = s + format3cstring(weeks[0], weeks[1], weeks[2],
  217.                                    colwidth, c).rstrip() + '\n' * l
  218.     return s[:-l] + '\n'
  219.  
  220. EPOCH = 1970
  221. _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
  222.  
  223. def timegm(tuple):
  224.     """Unrelated but handy function to calculate Unix timestamp from GMT."""
  225.     year, month, day, hour, minute, second = tuple[:6]
  226.     days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
  227.     hours = days*24 + hour
  228.     minutes = hours*60 + minute
  229.     seconds = minutes*60 + second
  230.     return seconds
  231.